import { getAddressList, removeAddress } from '@/services/address';
import { createOrder } from '@/services/orders';
import { colorStr, getQueryParams, selectOne } from '@/utils/utils';
import { Button, Collapse, Empty, message, Modal, Radio } from 'antd';
import { useCallback, useEffect, useState } from 'react';
import styles from '../index.less';
import ManageAddress from './ManageAddress';

interface Props {
  visible: boolean;
  willBuy: any[];
  moneyCount: string;
  onCancel: () => void;
  getCarList: () => void;
}

const AddressConfirm: React.FC<Props> = ({
  visible,
  onCancel,
  willBuy,
  moneyCount,
  getCarList,
}) => {
  let qs = getQueryParams();
  // 主题颜色的值
  const color = localStorage.getItem('color') || '#1a7721';
  const { Panel } = Collapse;
  const [valueRadio, setValueRadio] = useState<number>(1);
  const [manageAddress, setManageAddress] = useState<boolean>(false);
  const [list, setList] = useState<any[]>([]);

  const getList = useCallback(async () => {
    try {
      await getAddressList({ userid: qs.id }).then((res) => {
        setList(res);
      });
    } catch (error) {
      console.log(error);
    }
  }, [qs.id]);

  const createNewOrder = async () => {
    let willBuyCurr: any[] = [];
    willBuy.map((item) => {
      let currItem = { ...item, useraddress: valueRadio, username: qs.nickname };
      willBuyCurr.push(currItem);
    });
    await createOrder({ shopCars: JSON.stringify(willBuyCurr) }).then((res) => {
      if (res === '1') {
        message.error('该商品库存不足，支付失败！');
      } else {
        selectOne('1');
        setValueRadio(1);
        getCarList();
        message.success('支付成功！');
        onCancel();
      }
    });
  };

  const delectOne = async (id: string) => {
    try {
      await removeAddress({ id: id }).then(() => {
        message.success('删除成功！');
        getList();
        setManageAddress(false);
      });
      onCancel();
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    getList();
  }, [getList]);

  const onChange = (e: any) => {
    setValueRadio(e.target.value);
  };

  return (
    <Modal
      className={styles.addressContainer}
      visible={visible}
      onCancel={onCancel}
      width={700}
      centered
      footer={[
        <div key={'1'} className={styles.footBtns}>
          <Button onClick={onCancel}>取消</Button>
          <Button
            className={styles.btnBuy}
            style={{
              background: colorStr(3),
            }}
          >
            <div
              onClick={() => {
                if (valueRadio !== 1) {
                  createNewOrder();
                } else {
                  message.error('请选择地址！');
                }
              }}
            >
              前去支付
            </div>
            <span
              style={{
                backgroundColor: color,
              }}
            />
            <span
              style={{
                backgroundColor: color,
              }}
            />
            <span
              style={{
                backgroundColor: color,
              }}
            />
            <span
              style={{
                backgroundColor: color,
              }}
            />
          </Button>
        </div>,
      ]}
    >
      <div className={styles.content}>
        <Collapse bordered={false} defaultActiveKey={['1', '2']}>
          <Panel header="确认收货地址" key="1">
            {list.length === 0 ? (
              <Empty
                image={Empty.PRESENTED_IMAGE_SIMPLE}
                description={<span>暂无地址，请点击下方管理按钮进行新增</span>}
              />
            ) : (
              <Radio.Group onChange={onChange} value={valueRadio}>
                {list.map((item: any) => {
                  return (
                    <div key={item.userid}>
                      <Radio key={item.userid} value={item.id}>
                        {`${item.province} ${item.city} ${item.area} ${item.detail}
                    （${item.receiptname} 收）`}
                        <span style={{ color: color }}>&nbsp;&nbsp; {item.tel}</span>
                        {/* {item.isdefault === 'true' && <span>默认地址</span>} */}
                      </Radio>
                      <br />
                    </div>
                  );
                })}
              </Radio.Group>
            )}
            <div className={styles.manageAddress}>
              <Button
                style={{ border: `1px solid ${color}` }}
                onClick={() => {
                  setManageAddress(true);
                }}
              >
                管理收货地址
              </Button>
            </div>
          </Panel>
          <Panel header="价格明细" key="2">
            <div className={styles.saleCount}>商品总价：{moneyCount}</div>
            <div className={styles.goodsCount}>共{willBuy.length}件宝贝</div>
            <div className={styles.selfmoney}>您当前余额为：{qs.money.toFixed(2)}</div>
          </Panel>
        </Collapse>
        <ManageAddress
          visible={manageAddress}
          onCancel={() => {
            setManageAddress(false);
          }}
          address={list}
          getList={getList}
          style={{
            background: colorStr(3),
          }}
          color={color}
          delectOne={delectOne}
        />
      </div>
    </Modal>
  );
};

export default AddressConfirm;
